import sys
import os

# 获取项目根目录
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 将项目根目录添加到sys.path
sys.path.append(project_root)

import tkinter as tk
from tkinter import ttk, messagebox
from PIL import Image, ImageTk
import pandas as pd
from datetime import datetime
from utils.user import UserManager
import crawlers.international as international
import crawlers.national as national
import visualization.wordcloud_generator as wordcloud_generator

class InfoAnalyzerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("新浪新闻速看 - 登录与注册")
        self.root.iconbitmap("assets/logo.ico") 
        self.root.geometry("400x400")
        self.root.resizable(False, False)
        self.user_manager = UserManager()
        self.style = ttk.Style()
        self.style.theme_use('clam')
        self.style.configure("TLabel", font=("SimHei", 10))
        self.style.configure("TButton", font=("SimHei", 10))
        self.style.configure("TEntry", font=("SimHei", 10))
        self.create_login_ui()

    def create_login_ui(self):
        """登录界面"""
        self.clear_window(self.root)
        frame = ttk.LabelFrame(self.root, text="登录", padding=20)
        frame.pack(fill=tk.BOTH, expand=True)
        ttk.Label(frame, text="新浪新闻速看", font=("SimHei", 16, "bold")).pack(pady=10)
        ttk.Label(frame, text="用户名:").pack()
        self.login_username = ttk.Entry(frame, width=30)
        self.login_username.pack()
        ttk.Label(frame, text="密码:").pack()
        self.login_password = ttk.Entry(frame, width=30, show="*")
        self.login_password.pack()
        ttk.Button(frame, text="登录", command=self.handle_login).pack(pady=10)
        ttk.Button(frame, text="注册", command=self.create_register_ui).pack()
        self.status_label = ttk.Label(frame, text="", foreground="red")
        self.status_label.pack(pady=10)

    def create_register_ui(self):
        """注册界面"""
        self.clear_window(self.root)
        frame = ttk.LabelFrame(self.root, text="注册", padding=20)
        frame.pack(fill=tk.BOTH, expand=True)
        ttk.Label(frame, text="用户注册", font=("SimHei", 16, "bold")).pack(pady=10)
        self.register_username = ttk.Entry(frame, width=30)
        self.register_password = ttk.Entry(frame, width=30, show="*")
        self.register_confirm_password = ttk.Entry(frame, width=30, show="*")
        self.register_email = ttk.Entry(frame, width=30)
        for label, entry in zip(["用户名:", "密码:", "确认密码:", "邮箱:"],
                                [self.register_username, self.register_password,
                                 self.register_confirm_password, self.register_email]):
            ttk.Label(frame, text=label).pack()
            entry.pack()
        ttk.Button(frame, text="注册", command=self.handle_register).pack(pady=10)
        self.register_status_label = ttk.Label(frame, text="", foreground="red")
        self.register_status_label.pack()

    def handle_register(self):
        """处理注册"""
        u = self.register_username.get().strip()
        p = self.register_password.get()
        cp = self.register_confirm_password.get()
        e = self.register_email.get().strip()
        success, msg = self.user_manager.register(u, p, cp, e)
        if success:
            messagebox.showinfo("注册成功", msg)
            self.create_login_ui()
        else:
            self.register_status_label.config(text=msg)

    def handle_login(self):
        """处理登录"""
        u = self.login_username.get().strip()
        p = self.login_password.get()
        success, msg = self.user_manager.login(u, p)
        if success:
            self.open_news_main_ui(u)
        else:
            self.status_label.config(text=msg)

    def open_news_main_ui(self, username):
        """打开新闻主界面"""
        self.root.destroy()
        self.app_root = tk.Tk()
        self.app_root.title(f"新浪新闻速看 - 欢迎 {username}")
        self.app_root.geometry("900x700")
        self.app_root.resizable(False, False)
        self.app_root.iconbitmap("assets/logo.ico")

        # 顶部按钮
        btn_frame = ttk.Frame(self.app_root)
        btn_frame.pack(fill=tk.X, pady=10)
        ttk.Button(btn_frame, text="国内新闻", command=lambda: self.switch_news_frame('national')).pack(side=tk.LEFT, padx=10)
        ttk.Button(btn_frame, text="国际新闻", command=lambda: self.switch_news_frame('international')).pack(side=tk.LEFT, padx=10)
        ttk.Button(btn_frame, text="国内搜索", command=self.show_search_frame).pack(side=tk.LEFT, padx=10)
        
        # 内容容器
        self.content_container = ttk.Frame(self.app_root)
        self.content_container.pack(fill=tk.BOTH, expand=True)
        
        # 初始化所有框架
        self.news_frames = {
            'national': self.create_news_frame('national'),  # 国内新闻框架
            'international': self.create_news_frame('international'),  # 国际新闻框架
            'search': self.create_search_frame()  # 搜索框架
        }
        
        self.switch_news_frame('national')
        self.app_root.mainloop()

    def create_news_frame(self, news_type):
        """新闻概览界面"""
        frame = ttk.Frame(self.content_container, padding=10)
        today = datetime.now().date()
        csv_path = f"data/csv/{today}{news_type}_news.csv"
        wc_path = f"data/wordcloud/{news_type}_wordcloud.png"
        try:
            img = Image.open(wc_path).resize((400, 400))
            photo = ImageTk.PhotoImage(img)
            img_label = ttk.Label(frame, image=photo)
            img_label.image = photo
            img_label.pack()
        except FileNotFoundError:
            ttk.Label(frame, text="词云图不存在", foreground="red").pack()
        try:
            df = pd.read_csv(csv_path)
            box_frame = ttk.Frame(frame)
            box_frame.pack(fill=tk.BOTH, expand=True, pady=10)
            listbox = tk.Listbox(box_frame, font=("SimHei", 10), width=90, height=15)
            listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
            scrollbar = ttk.Scrollbar(box_frame, orient=tk.VERTICAL, command=listbox.yview)
            scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
            listbox.config(yscrollcommand=scrollbar.set)
            links = []
            for _, row in df.iterrows():
                listbox.insert(tk.END, f"{row['time']} | {row['title']}")
                links.append(row['url'])
            def open_link(event):
                index = listbox.curselection()
                if index:
                    import webbrowser
                    webbrowser.open(links[index[0]])
            listbox.bind('<Double-1>', open_link)
        except FileNotFoundError:
            ttk.Label(frame, text="新闻文件不存在", foreground="red").pack()
        return frame

    def show_search_frame(self):
        """显示搜索框架"""
        self.switch_news_frame('search')

    def create_search_frame(self):
        """创建搜索界面（使用100页国内新闻数据）"""
        frame = ttk.Frame(self.content_container, padding=10)
        
        # 搜索框
        search_frame = ttk.Frame(frame)
        search_frame.pack(fill=tk.X, pady=10)
        
        self.search_var = tk.StringVar()
        ttk.Entry(search_frame, textvariable=self.search_var, width=60, font=("SimHei", 11)).pack(side=tk.LEFT)
        ttk.Button(search_frame, text="搜索", command=self.perform_search).pack(side=tk.LEFT, padx=5)
        
        # 搜索结果展示
        result_frame = ttk.Frame(frame)
        result_frame.pack(fill=tk.BOTH, expand=True)
        
        # 配置Treeview列
        self.search_tree = ttk.Treeview(
            result_frame,
            columns=("time", "title", "summary"),
            show="headings",
            height=20
        )
        
        # 设置列属性
        self.search_tree.column("time", width=150, anchor="center")
        self.search_tree.column("title", width=300)
        self.search_tree.column("summary", width=450)
        
        self.search_tree.heading("time", text="发布时间")
        self.search_tree.heading("title", text="新闻标题")
        self.search_tree.heading("summary", text="新闻摘要")
        
        scrollbar = ttk.Scrollbar(result_frame, orient=tk.VERTICAL, command=self.search_tree.yview)
        self.search_tree.configure(yscrollcommand=scrollbar.set)
        
        self.search_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 双击打开
        self.search_tree.bind('<Double-1>', self.open_search_result)
        
        return frame

    def perform_search(self):
        """执行搜索功能（国内新闻数据中搜索）"""
        keyword = self.search_var.get().strip()
        if not keyword:
            messagebox.showwarning("提示", "请输入搜索关键词")
            return
        
        # 清空现有结果
        for item in self.search_tree.get_children():
            self.search_tree.delete(item)
        
        try:
            # 国内新闻数据文件读取
            csv_path = "data/csv/sina_national_news.csv"
            df = pd.read_csv(csv_path)
            
            # 标题和摘要
            results = df[
                df['title'].str.contains(keyword, case=False) |
                df['summary'].str.contains(keyword, case=False)
            ]
            
            # 网址URL
            self.search_results = []
            
            # 搜索结果显示
            for _, row in results.iterrows():
                self.search_tree.insert("", "end", values=(
                    row['time'],
                    row['title'],
                    row['summary'][:150] + "..." if len(row['summary']) > 150 else row['summary']
                ))
                self.search_results.append(row['url'])
                
            if len(results) == 0:
                self.search_tree.insert("", "end", values=("", "未找到相关新闻", ""))
                
        except FileNotFoundError:
            self.search_tree.insert("", "end", values=("", "新闻数据文件不存在", ""))
        except Exception as e:
            self.search_tree.insert("", "end", values=("", f"搜索出错: {str(e)}", ""))

    def open_search_result(self, event):
        """打开选中的搜索结果"""
        selected_item = self.search_tree.selection()
        if selected_item:
            index = self.search_tree.index(selected_item[0])
            if index < len(self.search_results):
                import webbrowser
                webbrowser.open(self.search_results[index])

    def switch_news_frame(self, news_type):
        """切换新闻框架"""
        for f in self.news_frames.values():
            f.pack_forget()
        self.news_frames[news_type].pack(fill=tk.BOTH, expand=True)

    

    def clear_window(self, win):
        """清洗窗口"""
        for widget in win.winfo_children():
            widget.destroy()

if __name__ == "__main__":
    root = tk.Tk()
    app = InfoAnalyzerApp(root)
    root.mainloop()